/*
 * @Author       : judapeng
 * @Date         : 2022-03-28 16:00:45
 * @LastEditors  : judapeng
 * @LastEditTime : 2022-03-28 16:08:28
 * @Description  : file content
 */
import vue from '@vitejs/plugin-vue';
import { defineConfig, createLogger } from 'vite';
import viteCompression from 'vite-plugin-compression';
import ElementPlus from 'unplugin-element-plus/vite';
import fs from 'fs';
import dotenv from 'dotenv';
import eslintPlugin from 'vite-plugin-eslint';

const { resolve } = require('path');

// 忽略构建时的警告信息，警告主要来源于原架子上的avue，由于大量使用无法优化掉
const logger = createLogger();
logger.warn = (msg, options) => {
	return;
};

export default ({ mode }) => {
	try {
		// 根据环境变量加载环境变量文件
		const file = dotenv.parse(fs.readFileSync(`.env.${mode}`));
		// 根据获取的key给对应的环境变量赋值
		for (const key in file) {
			process.env[key] = file[key];
		}
	} catch (e) {
		console.error(e);
	}
	const VITE_APP_BASE = process.env.VITE_APP_BASE;

	return defineConfig({
		base: VITE_APP_BASE,
		resolve: {
			alias: {
				'@': resolve(__dirname, 'src/'),
				components: resolve(__dirname, 'src/components'),
				styles: resolve(__dirname, 'src/styles'),
				utils: resolve(__dirname, 'src/utils'),
				'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
			},
		},
		server: {
			port: 2888,
			proxy: {
				'/api': {
					target: 'http://172.16.1.140:10001',
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, ''),
				},
			},
		},
		customLogger: logger,
		build: {
			assetsDir: './static',
			chunkSizeWarningLimit: 1500,
			minify: 'esbuild',
			cssCodeSplit: true,
			outDir: 'dist',
			rollupOptions: {
				output: {
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().split('node_modules/')[1].split('/')[0].toString();
						}
					},
				},
			},
			terserOptions: {
				compress: {
					// warnings: false,
					drop_console: true,
					drop_debugger: true,
					pure_funcs: ['console.log'],
				},
				output: {
					// 去掉注释内容
					comments: true,
				},
			},
			brotliSize: false,
		},
		plugins: [
			vue(),
			viteCompression({
				algorithm: 'brotliCompress',
			}),
			ElementPlus(),
			eslintPlugin({
				include: ['src/**/*.vue', 'src/**/*.js'], // 检查的文件
			}),
		],
	});
};
